package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.adapter.DubVideoAlbumAdapter;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.evaluate.bean.DubVideoCatalogue;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配音详情页面
 */
public class DubVideoDetailActivity extends BaseActivity {
    private static final String TAG = "DubVideoDetailActivity";
    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;
    private ImageView ivVideoPlay;
    private TextView tvDubVideoName, tvDubVideoDetail, tvDubVideoDownload;
    /**
     * 我要录音
     */
    private LinearLayout rlDubVideoRecord;
    /**
     * 下载进度
     */
    private LinearLayout rlDubVideoDownload;
    /**
     * 作业资源结构体
     */
    private WorkContent mWorkContent;
    /**
     * 视频本地保存地址
     */
    private String localVideoPath, localAudioPath, title;
    /**
     * 资源是否加载完成
     */
    private boolean isWorkContent = false;

    /**
     * 背景音是否需要下载
     */
    private boolean isNeedDownAudio = false;
    /**
     * 作业id（练习模式为“”）
     */
    private String workId = "";

    /**
     * 服务id
     */
    private int workType = 0;
    /**
     * 作业的班级id
     */
    private String classId = "0";

    /**
     * 作业内容id
     */
    private int contentId = 0;

    private GridView album_list;
    //是否来自作业
    private boolean isFromWork;

    private long startTime;
    //配音专辑适配器
    private DubVideoAlbumAdapter dubVideoAlbumAdapter;
    //配音专辑集合
    private List<DubVideoCatalogue> dubVideoCatalogueList = new ArrayList<>();
    //当前选中视频的versionId
    private String selectVersionId;

    @Override
    protected int setView() {
        return R.layout.activity_dub_video_detail;
    }

    @Override
    protected void findViews() {
        mKHBVideoPlayerStandard = findViewById(R.id.khb_content_video);
        ivVideoPlay = findViewById(R.id.iv_video_play);
        tvDubVideoName = findViewById(R.id.tv_dub_video_name);
        tvDubVideoDetail = findViewById(R.id.tv_dub_video_detail);
        rlDubVideoRecord = findViewById(R.id.rl_dub_video_record);
        rlDubVideoDownload = findViewById(R.id.rl_dub_video_download);
        tvDubVideoDownload = findViewById(R.id.tv_dub_video_download);
        album_list = findViewById(R.id.album_list);
    }

    @Override
    protected void initEvent() {
        ivVideoPlay.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                //播放
                mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
            }
        });
        rlDubVideoRecord.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                //下载完成
                if (isWorkContent) {
                    MeJumpManager.jumpToDubVideoRecordingActivity(EpaperConstant.REQUEST_CODE_GET_VIDEO_MASTER_STATE, R.string.go_back,
                            DubVideoDetailActivity.this, workId, mWorkContent, classId, contentId);
                } else {
                    showToastAlert("资源加载中...");
                }
            }
        });

        rlDubVideoDownload.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                //下载中
                showToastAlert("视频下载中...");
            }
        });

        album_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //selectVersionId = dubVideoCatalogueList.get(i).getVersionId();
                mWorkContent.setVersionId(dubVideoCatalogueList.get(i).getVersionId());
                getDubVideoDetailFromNet();
                //dubVideoAlbumAdapter.changeState(selectVersionId);
            }
        });
    }

    @Override
    protected void init() {
        mKHBVideoPlayerStandard.setNormalView(true);
        dubVideoAlbumAdapter = new DubVideoAlbumAdapter(dubVideoCatalogueList, selectVersionId, this);
        album_list.setAdapter(dubVideoAlbumAdapter);
        initData();
    }

    protected void initData() {
        Intent intent = getIntent();
        mWorkContent = (WorkContent) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        contentId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CONTENTID, 0);
        isFromWork = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_BOOLEAN, false);
        startTime = CWSys.getSharedLong(getStartTimeKey(), 0);
        if (isFromWork) {
            album_list.setVisibility(View.GONE);
        } else {
            album_list.setVisibility(View.VISIBLE);
        }
        if (startTime == 0) {
            if (null != mWorkContent) {
                startTime = mWorkContent.getStartTime();
                CWSys.setSharedLong(getStartTimeKey(), startTime);
            }
        }
        initView();
    }

    private void initView() {
        title = "视频详情";
        setTitleText(title);
        if (mWorkContent != null) {
            tvDubVideoName.setText(mWorkContent.getResourceName());
            workType = mWorkContent.getWorkType();
            getDubVideoDetailFromNet();
        }
    }

    public String getStartTimeKey() {
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        String userId = "";
        if (null != userInfo) {
            userId = userInfo.getUserId() + "";
        }
        String key = workId + mWorkContent.getVersionId() + userId + EApplication.BRAND_ID + SerializableManager.SerializeKey.SHARE_KET_WORK_NOW_DATA;
        return key;
    }

    @Override
    protected void loadData() {
//        getDubVideoDetailFromNet();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        KHBVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showProgressLoading() {
        showMiddleProgressBar(title);
    }

    private void dismissProgress() {
        hideMiddleProgressBar();
    }

    public void getDubVideoDetailFromNet() {
        showProgressLoading();
        EpaperDao.getInstance().getDubVideoDetail(mWorkContent.getVersionId(), new BaseExtCallBack(DubVideoDetailActivity.this) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                dismissProgress();
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                dismissProgress();
            }

            @Override
            public void success(Object data) {
                dismissProgress();
                try {
                    if (data != null && data instanceof WorkContent) {
                        mWorkContent = (WorkContent) data;
                        if ("".equals(mWorkContent.getBgAudioUrl())) {
                            mWorkContent.setBgAudioUrl("https://rimg3.ciwong.net/6v68/tools/audios/bgTemplate.mp3");
                        }
                        if (workType != 0) {
                            mWorkContent.setWorkType(workType);
                        }
                        dubVideoCatalogueList = mWorkContent.getPackageInfo().getPackagecatalogueList();
                        selectVersionId = mWorkContent.getVersionId();
                        dubVideoAlbumAdapter.setNewData(dubVideoCatalogueList, selectVersionId);
                        tvDubVideoDetail.setText(mWorkContent.getDetails());
                        tvDubVideoName.setText(mWorkContent.getResourceName());
                        isWorkContent = true;
                        initVideoView();
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });
    }

    /**
     * 加载视频视图
     */
    private void initVideoView() {
        IVUtils.setImageWidth200(mKHBVideoPlayerStandard.thumbImageView, mWorkContent.getCover());
        initDataView();
//        showGetSDcardPermissDialog();
    }

    /**
     * 设置视频播放资源
     */
    private void initDataView() {
        localVideoPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(mWorkContent.getVideoUrl());
        File targetFile = new File(localVideoPath);
        if ("".equals(mWorkContent.getBgAudioUrl())) {
            mWorkContent.setBgAudioUrl("https://rimg3.ciwong.net/6v68/tools/audios/bgTemplate.mp3");
        }
        if (mWorkContent.getBgAudioUrl() != null && !"".equals(mWorkContent.getBgAudioUrl())) {
            localAudioPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(mWorkContent.getBgAudioUrl()) + ".mp3";
            File targetAudioFile = new File(localAudioPath);
            if (!targetAudioFile.exists()) {
                isNeedDownAudio = true;
            } else {
                isNeedDownAudio = false;
            }
        }
        if (targetFile.exists()) {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(localVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
            rlDubVideoRecord.setVisibility(View.VISIBLE);
            rlDubVideoDownload.setVisibility(View.GONE);
            if (isNeedDownAudio) {
                rlDubVideoRecord.setVisibility(View.GONE);
                rlDubVideoDownload.setVisibility(View.VISIBLE);
                tvDubVideoDownload.setText("准备下载...");
                downAudioWork(mWorkContent.getBgAudioUrl(), localAudioPath);
            }
        } else {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(mWorkContent.getVideoUrl(), KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
            rlDubVideoRecord.setVisibility(View.GONE);
            rlDubVideoDownload.setVisibility(View.VISIBLE);
            tvDubVideoDownload.setText("准备下载...");
            downWork(mWorkContent.getVideoUrl(), localVideoPath);
        }
        mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                initDataView();
                            }
                        }
                    });
        } else {
            initDataView();
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_REQUEST_WRITESD_PERMISSION:
                    initDataView();
                    break;
            }
        }
    }

    private BaseDownloadTask task;

    public void downWork(String videoUrl, String localVideoPath) {
        //下载视频
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(2);
            if (null != task && task.isRunning()) {
                task.cancel();
            }
            task = mFileDownloader.create(videoUrl)
                    .setPath(localVideoPath)
                    .setAutoRetryTimes(3)
                    .setTag(videoUrl)
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener);
            task.start();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private BaseDownloadTask taskAudio;

    public void downAudioWork(String videoUrl, String localVideoPath) {
        //下载视频
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(2);
            if (null != taskAudio && taskAudio.isRunning()) {
                taskAudio.cancel();
            }
            taskAudio = mFileDownloader.create(videoUrl)
                    .setPath(localVideoPath)
                    .setAutoRetryTimes(3)
                    .setTag(videoUrl)
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener2);
            taskAudio.start();
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    FileDownloadListener fileDownloadListener = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_penging");
        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
            int isToal = 100;
            if (isNeedDownAudio) {
                isToal = 90;
            }
            tvDubVideoDownload.setText("下载中...（" + MeUtil.divide(MeUtil.divide(soFarBytes, totalBytes, 4) * isToal, 1, 2) + "%)");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            try {
                if (isNeedDownAudio) {
                    downAudioWork(mWorkContent.getBgAudioUrl(), localAudioPath);
                } else {
                    rlDubVideoRecord.setVisibility(View.VISIBLE);
                    rlDubVideoDownload.setVisibility(View.GONE);
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            tvDubVideoDownload.setText("下载失败");
            task.cancel();
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            CWLog.d("down", "down_warn");

        }
    };

    FileDownloadListener fileDownloadListener2 = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_penging");
        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            CWLog.d("down", "down_connected");
            tvDubVideoDownload.setText("下载中...（" + (90 + MeUtil.divide(MeUtil.divide(soFarBytes, totalBytes, 4) * 10, 1, 2)) + "%)");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            try {
                rlDubVideoRecord.setVisibility(View.VISIBLE);
                rlDubVideoDownload.setVisibility(View.GONE);
            } catch (Exception e) {
                e.getStackTrace();
            }
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            tvDubVideoDownload.setText("下载失败");
            task.cancel();
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            CWLog.d("down", "down_warn");

        }
    };
}